package controllers;

import static play.data.Form.form;

import java.io.InputStream;

import exceptions.NoUUIDException;
import interceptors.AuthCheckInterceptor;
import interceptors.DefaultInterceptor;
import interceptors.UserSessionInterceptor;
import play.data.DynamicForm;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.With;
import services.UserService;
import util.UserSession;
import collectors.wrapper.FilyouWrapper;

@With({DefaultInterceptor.class, UserSessionInterceptor.class, AuthCheckInterceptor.class})
public class Download extends Controller{

	private static final UserService userService = UserService.getInstance();
	private static final FilyouWrapper filyouWrapper = FilyouWrapper.getInstance();
	
	public static Result download(){
		try {
			UserSession userSession = userService.getUserSession(session());
			DynamicForm dynamicForm = form().bindFromRequest();
			String path = dynamicForm.get("path");
			
			InputStream file = filyouWrapper.download(userSession.getUser().filyouId, path);
			return ok (file);
			
		} catch (NoUUIDException e) {
			e.printStackTrace();
			return unauthorized();
		}
	}
	
}
